// Include header files for S3E (core system) and IwGx (rendering) modules
#include "s3e.h"
#include "IwGx.h"
#include "IwGxFont.h"
#include "IwUI.h"
#include "IwUIAnimation.h"
#include "IwUIController.h"
#include "IwUIButton.h"
#include "IwUICheckbox.h"
#include "IwUIElement.h"
#include "IwUIEvent.h"
#include "IwUILabel.h"
#include "IwUISlider.h"
#include "IwUIView.h"
#include "IwUIProgressBar.h"
#include "IwUIPropertySet.h"
#include "s3eKeyboard.h"
#include "IwUISoftKeyboard.h"
#include "IwUITextInput.h"
#include "IwResManager.h"
#include "sqlite3.h"

// Example Includes
#include "DatabaseHandler.h"


#include "CppSqlWrapper.h"
#include "s3eFile.h"
#include "s3eTimer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctime>
//#include <string>
#include <sstream>

using namespace std;


// Externs
extern bool g_IwTextureAssertPowerOf2;

enum TaskType{ Import, Export };
// Globals
bool g_Quit = false;
CIwArray<class CDataBinding*> g_NotifyBindings;
const char* DB_FILE_NAME = "sqlite1.sdb";
const char* OUTPUT_FILE_NAME = "test.log";
s3eFile* output_file;
s3eFile* dataFile;
TaskType g_Task = Import;// default Import
char* m_RootElement = "RootElement";
char* m_Input = "";
double m_MoneyImport = 0;
double m_MoneyExport = 0;

class CCommandHandler;
// Create singletons
CDatabaseHandler* pDatabaseHandler;
CCommandHandler* pCommandHandler;
CIwResGroup* pResGroup;

void ExampleInit();
void ExampleShutDown();
void ExampleRender();
bool ExampleUpdate();
void InitDataBinding();
void UpdateDataBinding();
void InitSQLite();

#define MS_PER_FRAME (1000 / 25)

//static CIwMaterial* g_CursorMaterial = NULL;

// Globals UI
CIwUIElement* rootElement;
CIwUIImage* ImageMoney;
CIwUILabel* LabelMoney;
CIwUILabel* LabelInput;
CIwUIButton* TaskImport;
CIwUIButton* TaskExport;
CIwUILabel* LabelRemain;
CIwUIButton* Button_Dot;

CIwUIButton* s_Button = NULL;
//CIwUIElement* g_Screen;
int s_ClickCounter = 0;

string dToStr(double d)
{
  std::string s;
  // convert double b to string s
  { std::ostringstream ss;
    ss << d;
    s = ss.str();
  }
  return s;
}

char* removeRight(char* str)
	{
		int iEnd = 0;
		int i = strlen(str) -1;
		for(i ; i > 0; i--)
		{
			if(str[i] == '.')
			{
				break;
			}
			if(str[i] != '0' && iEnd == 0)
			{
				iEnd = i;
			}
		}
		// have dot (.)
		if(i > 0 && iEnd == 0)
		{
			iEnd = i - 1;
		}
		else if(iEnd == 0)
		{
			str = "0";
		}
		str[iEnd + 1] = '\0';
		return str;
	}

char* dbtostr(double d)
{
		char* result = new char[100];
		sprintf(result,"%1.2lf",d);
		removeRight(result);
		return result;
}

double strtodb(char* str)
{
		return strtod(str, NULL);
}

void readFileData()
{
	output_file = s3eFileOpen(OUTPUT_FILE_NAME, "rt");
	int32 fileSize = s3eFileGetSize( output_file );
	if(fileSize < 0)
	{
		s3eFileClose(output_file);
		return;
	}
	char* line = new char[fileSize];
	s3eFileRead(line, fileSize,1, output_file);
	s3eFileClose(output_file);
	//s3eFree(line);
	if(fileSize > 0)
	{
		if(line[0] == '2')
			g_Task = Export;
		char* result = new char[50];
		int idx = 0;
		for(int i = 2;i<strlen(line);i++)
		{
			if(line[i] == '|')
			{
				result[idx] = '\0';
				m_MoneyImport = strtodb(result);
				delete[] result;
				char* result = new char[50];
				idx = 0;
			}
			else
			{
				result[idx++] = line[i];
			}
		}
		m_MoneyExport = strtodb(result);

		delete[] result;
	}
	delete[] line;
}

void writeFileData()
{
		char* str = new char[255];
		char* strDb;
		strcpy(str,"1|");
		if(g_Task == Export)
			strcpy(str,"2|");
		strDb = dbtostr(m_MoneyImport);
		strcat(str, strDb);
		delete[] strDb;
		strcat(str, "|");
		strDb = dbtostr(m_MoneyExport);
		strcat(str, strDb);
		delete[] strDb;
	output_file = s3eFileOpen(OUTPUT_FILE_NAME, "w");
	s3eFilePrintf(output_file, "%s\r\n", str);
	s3eFileClose(output_file);
		delete[] str;
}

class CCommandHandler
{
public:
    CCommandHandler()
    {
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickQuit, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickTask, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickAction, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickFunction, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickCancel, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickBack, CIwUIElement*)
        IW_UI_CREATE_VIEW_SLOT1(this, "CCommandHandler", CCommandHandler,
            OnClickEnter, CIwUIElement*)
    }

    ~CCommandHandler()
    {
        IW_UI_DESTROY_VIEW_SLOTS(this)
    }


	void OnClickTaskPublic(CIwUIElement* element)
	{
		OnClickTask(element);
	}
private:
    void OnClickTask(CIwUIElement* element)
    {
		char* textureName;
		double money;
		if(element == TaskImport)
		{
			money = m_MoneyImport;
			g_Task = Import;
			textureName = "import";
			TaskImport->SetEnabled(false);
			TaskExport->SetEnabled(true);
		}
		else if(element == TaskExport)
		{
			money = m_MoneyExport;
			g_Task = Export;
			textureName = "export";
			TaskExport->SetEnabled(false);
			TaskImport->SetEnabled(true);
		}
		char* sMoney = new char[100];
		sprintf(sMoney,"%1.2lf",money);
		removeRight(sMoney);
		LabelMoney->SetCaption(sMoney);
		CIwTexture* pTexture = (CIwTexture*)pResGroup->GetResNamed(textureName, "CIwTexture");
		ImageMoney->SetTexture(pTexture);
		//delete[] textureName;
		delete[] sMoney;
    }
    void OnClickAction(CIwUIElement* element)
    {
		const char* lblInput = LabelInput->GetCaption();
		if(strlen(lblInput) > 9)// Accept 10 number.
			return;
		const char* number = ((CIwUIButton*)element)->GetCaption();
		char* inputstr = new char[strlen(lblInput) + strlen(number)];
		// append string.
		strcpy(inputstr, lblInput);
		if(strcmp(lblInput, "0") || !strcmp(number, "."))//lblInput != "0"
		{
			strcat(inputstr, number);
			if(!strcmp(number, "."))
			{
				Button_Dot->SetEnabled(false);
			}
		}
		// replace string.
		else if(strcmp(number,"0") && strcmp(number, "00"))//number != "0" && number != "00"
		{
			strcpy(inputstr, number);
		}
		LabelInput->SetCaption(inputstr);
		delete[] inputstr;
   }
    void OnClickFunction(CIwUIElement* element)
    {
		if(element == TaskImport)
		{
			LabelRemain->SetCaption("Import");
		}
		else if(element == TaskExport)
		{
			LabelRemain->SetCaption("Export");
		}
    }
    void OnClickCancel(CIwUIElement* element)
    {
		LabelInput->SetCaption("0");
	}
    void OnClickBack(CIwUIElement* element)
    {
		CIwUIButton* btn = (CIwUIButton*)element;
		const char* lblInput = LabelInput->GetCaption();
		int len = strlen(lblInput);
		if(len == 1)
		{
			LabelInput->SetCaption("0");
			return;
		}
		char c = lblInput[len-1];
   		char* inputstr1 = new char[len];
		strncpy(inputstr1, lblInput, len);
		inputstr1[len - 1] = '\0';
		LabelInput->SetCaption(inputstr1);
		if(c == '.')
		{
			Button_Dot->SetEnabled(true);
		}
		delete[] inputstr1;
    }

	void OnClickEnter(CIwUIElement* element)
    {
		CIwUIButton* btn = (CIwUIButton*)element;
		const char* lblInput = LabelInput->GetCaption();
		double money = strtod(lblInput, NULL);
		if(g_Task == Import)
		{
			m_MoneyImport += money;
			money = m_MoneyImport;
		}
		else
		{
			m_MoneyExport += money;
			money = m_MoneyExport;
		}
		char* sMoney = new char[100];
		sprintf(sMoney,"%1.2lf",money);
		removeRight(sMoney);
		LabelMoney->SetCaption(sMoney);
		sprintf(sMoney,"%1.2lf",m_MoneyImport - m_MoneyExport);
		removeRight(sMoney);
		LabelRemain->SetCaption(sMoney);
		LabelInput->SetCaption("0");
		Button_Dot->SetEnabled(true);
		delete sMoney;
		// Write into data store.
		writeFileData();
	}

    void OnClickQuit(CIwUIElement* element)
    {
			g_Quit = true;
    }
};

void output() { // Print a blank line
	s3eFilePrintf(output_file, "\r\n");
	printf("\n");
}
void output(const char* fmt, ...) {
	s3eFilePrintf(output_file, "%s\r\n", fmt);
	printf("%s\n", fmt);
}

void output1(const char* fmt, ...) {
	static char out_str[512];
	va_list args;
	va_start(args, fmt);
	vsprintf(out_str, fmt, args);
	s3eFilePrintf(output_file, "%s\r\n", out_str);
	printf("%s\n", out_str);
	va_end(args);
}


int main1()
{
    g_IwTextureAssertPowerOf2 = false;
    g_Quit = false;

    // Initialize IwUI
    IwUIInit();
    IwGxSetColClear(0xf0, 0xf0, 0xf0, 0xff);

    IW_CLASS_REGISTER(CDataBinding);

    pDatabaseHandler = new CDatabaseHandler;
    new CIwUIView;
    new CIwUIController;
    pCommandHandler = new CCommandHandler;
	
    // Load database
    bool ret = pDatabaseHandler->OpenDatabaseInMemory();
    IwAssertMsg(UI, ret, ("Failed to open databse"));
    (void) ret;

    // Ensure we have table
    if (!pDatabaseHandler->TableExists("tbl"))
    {
        const char* pSQL = "create table tbl(id integer primary key, val int);";
        pDatabaseHandler->Exec(pSQL);

        // Put some data in the table
        pSQL = "insert into tbl values (1, 25);";
        pDatabaseHandler->Exec(pSQL);
    }

    // Load resources
    pResGroup = IwGetResManager()->LoadGroup("HelloWorld.group");

    // Create main page
    CIwUIElement* pTable = CIwUIElement::CreateFromResource("RootElement");
    IwGetUIView()->AddElementToLayout(pTable);

    // Pick an element to have focus by default
	CIwUIElement* pFocusElement = pTable->GetChildNamed("Table")->GetChildNamed("Slider");
    IwGetUIView()->RequestFocus(pFocusElement);

    uint64 lastTime = s3eTimerGetMs();
    while (!g_Quit)
    {
        IwGxClear(IW_GX_COLOUR_BUFFER_F | IW_GX_DEPTH_BUFFER_F);

        IwGetUIController()->Update();

        // Calculate an update time step.
        uint64 currentTime = s3eTimerGetMs();
        int32 updateTime = currentTime > lastTime ?
            MIN((int32)(currentTime - lastTime), 1000) : 0;
        lastTime = currentTime;

        // This isn't great but must be a asynchronous
        while (g_NotifyBindings.size())
        {
            CDataBinding* pBinding = g_NotifyBindings.pop_back_get();
            pBinding->NotifyElementPropertyChanged();
        }

        // Update & render
        IwGetUIView()->Update(updateTime);
        IwGetUIView()->Render();

        // Flush render queue
        IwGxFlush();
        IwGxSwapBuffers();

        // Standard device interaction
        s3eDeviceYield();
        s3eKeyboardUpdate();
        s3ePointerUpdate();

        // Check for quit request
        g_Quit |= (s3eDeviceCheckQuitRequest()!=0);
    }

    // Destroy resources
    IwGetResManager()->DestroyGroup(pResGroup);

    // Close database
    pDatabaseHandler->CloseDatabase();

    // Destroy singletons
    delete pCommandHandler;
    delete IwGetUIController();
    delete IwGetUIView();
    delete pDatabaseHandler;

    IW_CLASS_REMOVE(CDataBinding);

    // Free array
    g_NotifyBindings.clear_optimised();

    // Terminate IwUI
    IwUITerminate();
    return 0;
}



// Standard C-style entry point. This can take args if required.
int main()
{
    IwGxInit();

    // Example main loop
    ExampleInit();
	
    // Set screen clear colour
    IwGxSetColClear(0xff, 0xff, 0xff, 0xff);
    IwGxPrintSetColour(128, 128, 128);
	g_Quit = false;
    while (!g_Quit)
    {
        s3eDeviceYield(0);
        s3eKeyboardUpdate();
        s3ePointerUpdate();

        int64 start = s3eTimerGetMs();

        bool result = ExampleUpdate();
        if  (
            (result == false) ||
            (s3eKeyboardGetState(s3eKeyEsc) & S3E_KEY_STATE_DOWN) ||
            (s3eKeyboardGetState(s3eKeyAbsBSK) & S3E_KEY_STATE_DOWN) ||
            (s3eDeviceCheckQuitRequest())
            )
            break;

        // Clear the screen
        IwGxClear(IW_GX_COLOUR_BUFFER_F | IW_GX_DEPTH_BUFFER_F);
        //RenderButtons();
        //RenderCursor();
        //RenderSoftkeys();
        ExampleRender();

        // Attempt frame rate
        while ((s3eTimerGetMs() - start) < MS_PER_FRAME)
        {
            int32 yield = (int32) (MS_PER_FRAME - (s3eTimerGetMs() - start));
            if (yield<0)
                break;
            s3eDeviceYield(yield);
        }
        
		// Check for quit request
        g_Quit |= (s3eDeviceCheckQuitRequest()!=0);
	}

    //delete g_CursorMaterial;
    ExampleShutDown();
    //DeleteButtons();
    IwGxTerminate();
    return 0;
}


void InitComponent(const char* screen)
{
    //Find the dialog template
    rootElement = (CIwUIElement*)IwGetResManager()->GetResNamed(screen, "CIwUIElement");

    if (!rootElement)
        return;

    //Remove the old screen
    if (rootElement)
        IwGetUIView()->DestroyElements();

    //And instantiate it
    rootElement = rootElement->Clone();
    IwGetUIView()->AddElement(rootElement);
    IwGetUIView()->AddElementToLayout(rootElement);

	ImageMoney = (CIwUIImage*)rootElement->GetChildNamed("TitlePanel")->GetChildNamed("ImageMoney");
	LabelMoney = (CIwUILabel*)rootElement->GetChildNamed("TitlePanel")->GetChildNamed("LabelMoney");
	LabelInput = (CIwUILabel*)rootElement->GetChildNamed("TitlePanel")->GetChildNamed("LabelInput");
	TaskImport = (CIwUIButton*)rootElement->GetChildNamed("TaskPanel")->GetChildNamed("TaskImport");
	TaskExport = (CIwUIButton*)rootElement->GetChildNamed("TaskPanel")->GetChildNamed("TaskExport");
	LabelRemain = (CIwUILabel*)rootElement->GetChildNamed("TaskPanel")->GetChildNamed("LabelRemain");
	Button_Dot = (CIwUIButton*)rootElement->GetChildNamed("ActionPanel")->GetChildNamed("Button_Dot");
	//LabelRemain->SetCaption("222222");

	// read from data store.
	readFileData();

	if(g_Task == Import)
		pCommandHandler->OnClickTaskPublic(TaskImport);
	else if(g_Task == Export)
		pCommandHandler->OnClickTaskPublic(TaskExport);

	char* sMoneyTotal = dbtostr(m_MoneyImport - m_MoneyExport);
	LabelRemain->SetCaption(sMoneyTotal);
	delete[] sMoneyTotal;
}

void DestroyComponent()
{
//delete ImageMoney;
//delete LabelMoney;
//delete LabelInput;
//delete TaskImport;
//delete TaskExport;
//delete LabelRemain;
//delete Button_Dot;
	s3eFree(rootElement);
}
//-----------------------------------------------------------------------------
//void CController::OnClickButton(CIwUIElement* button)
//{
//CIwPropertyString pString;
//button->GetProperty("name", pString);
//if (strcmp(pString.c_str(), "btnExit") == 0)
//DoSomethingHere();
//}

//-----------------------------------------------------------------------------
class MyButtonEventHandler : public CIwUIElementEventHandler
{
public:
    //HandleEvent is passed up the element hierarchy
    virtual bool HandleEvent(CIwEvent* pEvent)
    {
        //if (pEvent->GetID() == IWUI_EVENT_BUTTON)
        //{
        //    char captionString[0x40];
        //    sprintf(captionString, "I have been\n clicked %i times",++s_ClickCounter);
        //    s_Button->SetCaption(captionString);

        //    //return true, as event has been handled
        //    return true;
        //}

        return false;
    }

    //FilterEvent is passed down the element hierarchy
    virtual bool FilterEvent(CIwEvent* pEvent)
    {
		//switch ( pEvent->GetID() )
		//{
		//case IWUI_EVENT_BUTTON:
		//{
		//CIwUIButton* pButton = ((CIwUIEventButton*)pEvent)->GetButton();
		//if ( pButton == (CIwUIButton*)IwGetUIView()->GetChildNamed("my_button") )
		//{
		//// Button named "my_button" was clicked
		//}
		//break;
		////return false, since filtering is not necessary
        return false;
    }
};


//-----------------------------------------------------------------------------
void ExampleInit()
{
    //Initialise the IwUI module
    IwUIInit();

    //Instantiate the view and controller singletons.
    //IwUI will not instantiate these itself, since they can be subclassed to add functionality.
    new CIwUIController;
    new CIwUIView;

	//// Test DataBiding.
	//InitDataBinding();
	// Test SQLite.
	//InitSQLite();

	// Support CDataBinding in resource.
	IW_CLASS_REGISTER(CDataBinding);
	// singletons
    pDatabaseHandler = new CDatabaseHandler;
	pCommandHandler = new CCommandHandler;

    //Load group which contains the ui specifications
    pResGroup = IwGetResManager()->LoadGroup("HelloWorld.group");

	////Set the default style sheet.			<Option>
	//CIwResource* pResource = IwGetResManager()->GetResNamed("iwui", IW_UI_RESTYPE_STYLESHEET);
	//IwGetUIStyleManager()->SetStylesheet(IwSafeCast<CIwUIStylesheet*>(pResource));

	//InitComponent("main");
	InitComponent(m_RootElement);

}
//-----------------------------------------------------------------------------
void ExampleShutDown()
{
    // Destroy resources
    IwGetResManager()->DestroyGroup(pResGroup);
	//IwResManagerTerminate();

    // Close database
    //pDatabaseHandler->CloseDatabase();

    // Destroy singletons
    delete pCommandHandler;
	//DestroyComponent();
    delete IwGetUIController();
    delete IwGetUIView();
    delete pDatabaseHandler;

    IW_CLASS_REMOVE(CDataBinding);

    // Free array
    g_NotifyBindings.clear_optimised();
	
	//delete IwGetUIController();
 //   delete IwGetUIView();

    //Terminate the IwUI module
    IwUITerminate();
}
//-----------------------------------------------------------------------------
bool ExampleUpdate()
{
	//UpdateDataBinding();

    //Update the controller (this will generate control events etc.)
    IwGetUIController()->Update();

    //Update the view (this will do animations etc.) The example framework has
    //a fixed framerate of 20fps, so we pass that duration to the update function.
    IwGetUIView()->Update(1000/20);

    return true;
}
//-----------------------------------------------------------------------------
void ExampleRender()
{
    //Render the UI
    IwGetUIView()->Render();

    //Flush IwGx
    IwGxFlush();

    //Display the rendered frame
    IwGxSwapBuffers();
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void InitDataBinding()
{
	strcpy(m_RootElement,"DataBinding");

	//char* fileName = "sqlite1.sdb";
	bool ret = pDatabaseHandler->OpenDatabase(DB_FILE_NAME);
	//bool ret = pDatabaseHandler->OpenDatabaseInMemory();
	IwAssertMsg(UI, ret, ("Failed to open databse"));
    (void) ret;

    const char* pSQL = "create table tbl(id integer primary key, val int);";
    // Ensure we have table
    if (!pDatabaseHandler->TableExists("tbl"))
    {
        pDatabaseHandler->Exec(pSQL);

    }
	int iCount = 0;
	pSQL = "select count(*) from tbl;";
	if(pDatabaseHandler->ExecScalar(pSQL, iCount) && iCount < 1)
	{
        // Put some data in the table
        pSQL = "insert into tbl values (1, 25);";
        pDatabaseHandler->Exec(pSQL);
	}

}

void UpdateDataBinding()
{
	// This isn't great but must be a asynchronous
    while (g_NotifyBindings.size())
    {
        CDataBinding* pBinding = g_NotifyBindings.pop_back_get();
        pBinding->NotifyElementPropertyChanged();
    }
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void InitSQLite()
{
	//try
	//{
	// Always start this example with an empty database:
	if (s3eFileCheckExists(DB_FILE_NAME) == S3E_TRUE)
		s3eFileDelete(DB_FILE_NAME);

	// Create a blank logfile to save all output:
	output_file = s3eFileOpen(OUTPUT_FILE_NAME, "w");

	// Open or create the database:
	SqlDatabase db(DB_FILE_NAME, false);

	////////////////////////////////////////////////////////////////////////////////
	// Example of checking if a table exists
	////////////////////////////////////////////////////////////////////////////////
	output("--------- tableExists() method and basic sqlExec() usage --------\n");

	output("Checking if the 'employee' table exists: %s", db.tableExists("employee") ? "yes" : "no");
	output("Creating employee table");
	//db.sqlExec("create table employee(id int, name char(20), age int);");create table employee(id integer primary key, name char(20), age numeric);
	db.sqlExec("create table employee(id integer primary key, name char(20), age numeric);");
	output("Checking if the 'employee' table exists: %s", db.tableExists("employee") ? "yes" : "no");

	int nRowsToCreate = 35; // Reduce this number a lot for this part... 
	struct Name { char m_nameStr[20]; };
	Name *names = new Name[nRowsToCreate];
	
	output("Inserting %d randomly generated records", nRowsToCreate);

	SqlStatement insert_employee = db.sqlCompile("insert into employee (name, age) values (?, ?);");
	for (int i = 0; i < nRowsToCreate; i++) {
	insert_employee
		.bind(names[i].m_nameStr)
		.bind(rand() % 50 + 18)
		.execute(); 
	}
	// Note: insert_employee will be automatically free when it goes out of scope... or we could call insert_employee.destroy()

	output("Done.");


	////////////// Now lets try SELECTing some results: //////
	SqlStatement results;

	int age_split = 50 + (rand() % 5);

	output("Now, let's find all the employees under age %d:", age_split);
	///// Example method 1: use sqlQuery() ////////////
	results = db.sqlQuery("SELECT id,name,age FROM employee WHERE age < %d", age_split); // 
	if (!results.hasRow())
		output("None found???");
	else {
		// Here I'm showing how nextRow() works with a do...while loop, since we already know there's at least one row
		do {
			output("Employee %5d: %-18s (age %d)", 
				results.currentRow().getIntField(0),
				results.currentRow().getStringField(1),
				results.currentRow().getIntField("age") // Note you can reference a field by column index or by name
			);
		} while (results.nextRow());
	}

	output("");
	output("Now, let's find all the employees age %d or over:", age_split);
	///// Example method 2: use compileStatement()  ////////////
	results = db.sqlCompile("SELECT id,name,age FROM employee WHERE age >= ?").bind(age_split).execute();
	while(results.hasRow()) {
		output("Employee %5d: %-18s (age %d)", 
			results.currentRow().getIntField(0),
			results.currentRow().getStringField(1),
			results.currentRow().getIntField("age") // Note you can reference a field by column index or by name
		);
		results.nextRow();
	}
	// Destroy.
	delete[] names; 
	//delete names;
	insert_employee.destroy();
	results.destroy();
	db.close();
	//} catch(SqlDatabaseException e) {
	//	output("Exception: %s", e.what());
	//}
	s3eFileClose(output_file);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void ChangeUI()
{
	//CIwUIElement* lable = (CIwUIElement*) CIwUIElement::CreateFromResource("RootElement");
			//IwGetUIView()->AddElement(lable);

	    //// This isn't great but must be a asynchronous
     //   while (g_NotifyBindings.size())
     //   {
     //       CDataBinding* pBinding = g_NotifyBindings.pop_back_get();
     //       pBinding->NotifyElementPropertyChanged();
     //   }


 //   //Load button
 //   s_Button = (CIwUIButton*) CIwUIElement::CreateFromResource("EventButton");

 //   //Attach eventhandler to button
 //   s_Button->AddEventHandler(new MyButtonEventHandler);

	////Add the label to the UIView singleton
 //   IwGetUIView()->AddElement(s_Button);

			//CIwUILabel* lable = (CIwUILabel*) CIwUIElement::CreateFromResource("LabelButton");
			////s_Button->AddChild(lable);
			//IwGetUIView()->AddElement(lable);

			//CIwUIImage* image = (CIwUIImage*) CIwUIElement::CreateFromResource("ImageButton");
			////s_Button->AddChild(image);
			//IwGetUIView()->AddElement(image);

			////CIwResGroup* pLevel1Group = IwGetResManager()->GetGroupNamed("HelloWorld");
			////CIwTexture* pBackgroundTexture = (CIwTexture*)pLevel1Group->GetResNamed("success", "CIwTexture");
			////IwUISetPropertyOnInlineStyle(s_Button, "buttonUp", "texture", pBackgroundTexture);

			////CIwUIImage* image = new CIwUIImage();
			////image->SetTexture(pBackgroundTexture);
			////s_Button->AddChild(image);
}

